package com.uetoken.cn.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Environment;
import android.support.v4.widget.NestedScrollView;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.uetoken.cn.MainActivity;
import com.uetoken.cn.R;
import com.uetoken.cn.activity.SplashActivity;
import com.uetoken.cn.network.DownloadProgressListener;
import com.uetoken.cn.network.OkHttpUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.text.DecimalFormat;
import java.util.List;

import okhttp3.Response;

/**
 * @author 谢杨
 * @time 2018/8/8 11:34
 * @class 描述:app升级
 */
public class AppUpdate {
    private Activity mActivity;
    /**
     * apk保存路径
     */
    private String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
    /**
     * apk名字
     */
    private String fileName;

    public AppUpdate(Activity activity) {
        this.mActivity = activity;
    }

    /**
     * 显示升级提示框
     *
     * @param url
     * @param remark
     * @param isMandatoryUpdate
     */
    public void showUpdateDialog(final String url, String version, String remark, boolean isMandatoryUpdate) {
        fileName = "ue_token" + version;

        View view = View.inflate(mActivity, R.layout.dialog_update, null);
        final Dialog updateDialog = new Dialog(mActivity, R.style.loading_dialog);
        updateDialog.setContentView(view);
        updateDialog.setCancelable(false);
        updateDialog.setCanceledOnTouchOutside(false);
        //修正后代码
        if(ActivityUtils.isActivityAlive(mActivity)){
            updateDialog.show();
        }


        RelativeLayout topLayout = view.findViewById(R.id.topLayout);
        LinearLayout buttonLayout = view.findViewById(R.id.buttonLayout);
        TextView mTvNewVersion = view.findViewById(R.id.tv_dialog_update_new_version);
        TextView mTvContent = view.findViewById(R.id.tv_dialog_update_content);
        TextView mTvDownload = view.findViewById(R.id.tv_dialog_update_download);
        TextView mTvThinkAgain = view.findViewById(R.id.tv_dialog_update_think_again);
        NestedScrollView scrollView = view.findViewById(R.id.scrollView);

        int height = (int) (ScreenUtils.getScreenHeight() * 0.8);
        int topHeight = SizeUtils.getMeasuredHeight(topLayout);
        int buttonHeight = SizeUtils.getMeasuredHeight(topLayout);
        int contentHeight = height - topHeight - buttonHeight;
        mTvContent.setMaxHeight(contentHeight);
        //      设置内容可滚动
//        mTvContent.moveCursorToVisibleOffset()
        mTvContent.setMovementMethod(ScrollingMovementMethod.getInstance());

        mTvNewVersion.setText(mActivity.getResources().getString(R.string.str_found_new_version) + version);
        mTvContent.setText(remark.replace("\\n", "\n"));
        if (isMandatoryUpdate) {
            mTvThinkAgain.setVisibility(View.GONE);
        }

        mTvDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
                downLoadAPK(url);
            }
        });

        mTvThinkAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
                mActivity.startActivity(new Intent(mActivity, MainActivity.class));
                mActivity.finish();
            }
        });
    }

    /**
     * 下载apk
     *
     * @param url
     */
    private void downLoadAPK(final String url) {

        AndPermission.with(mActivity).runtime().permission(Permission.Group.STORAGE).onGranted(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                View view = View.inflate(mActivity, R.layout.dialog_progressbar, null);
                final Dialog dialog = new Dialog(mActivity, R.style.loading_dialog);
                dialog.setContentView(view);
                dialog.setCancelable(false);
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();

                final ProgressBar progressBar = view.findViewById(R.id.pb_progress);
                final TextView mTvCurrentPercent = view.findViewById(R.id.tv_current_percent);
                final TextView mTvCurrentAndTotalSize = view.findViewById(R.id.tv_current_and_total_size);

                final DecimalFormat decimalFormat = new DecimalFormat("#.0");
                OkHttpUtils.getInstance().fileDownload(new DownloadProgressListener() {
                    @Override
                    public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
                        final int currentSize = (int) bytesRead;
                        final int totalSize = (int) contentLength;
                        final int percent = (int) (((float) currentSize / (float) totalSize) * 100);
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTvCurrentPercent.setText(percent + "%");
                                mTvCurrentAndTotalSize.setText(decimalFormat.format((float) currentSize / 1024) + "KB/" + decimalFormat.format((float) totalSize / 1024 / 1024) + "M");
                                progressBar.setProgress(currentSize);
                                progressBar.setMax(totalSize);
                            }
                        });
                    }

                    @Override
                    public void onDownloadSuccess(Response response) {
                        dialog.dismiss();
                        AppUtils.installApp(filePath + fileName);
                    }

                    @Override
                    public void onDownloadFailed(Exception e) {
                        ToastUtils.showShort(mActivity.getResources().getString(R.string.str_download_fail));
                        dialog.dismiss();
                    }
                }, url, filePath, fileName);
            }
        }).onDenied(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                ToastUtils.showShort(mActivity.getResources().getString(R.string.str_download_fail));
            }
        }).start();
    }

}
